package com.atguigu.edu.app.dws;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.bean.TrafficVideoPlayBean;
import com.atguigu.edu.util.*;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

public class DwsTrafficVideoPlayWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        // TODO 2 设置状态后端
        /*
            env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
            env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
            env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
            env.setStateBackend(new HashMapStateBackend());
            env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
            System.setProperty("HADOOP_USER_NAME", "atguigu");
        */

        String topicName = "dwd_traffic_video_play_detail";
        String groupId = "dws_traffic_video_play_window";

        DataStreamSource<String> videoStream = env.addSource(KafkaUtil.getFlinkKafkaConsumer(topicName, groupId));

        // TODO 3 转换为对应的javaBean
        SingleOutputStreamOperator<TrafficVideoPlayBean> beanStream = videoStream.map(new MapFunction<String, TrafficVideoPlayBean>() {
            @Override
            public TrafficVideoPlayBean map(String s) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(s);
                String mid = jsonObject.getString("mid");
                Long playSec = jsonObject.getLong("playSec");
                String videoId = jsonObject.getString("videoId");
                Long ts = jsonObject.getLong("ts");

                TrafficVideoPlayBean trafficVideoPlayBean = TrafficVideoPlayBean.builder()
                        .mid(mid)
                        .playedtimesum(playSec)
                        .videoId(videoId)
                        .videoplayedcount(1L)
                        .personwatchedcount(1L)
                        .ts(ts)
                        .build();

                return trafficVideoPlayBean;
            }
        });

        SingleOutputStreamOperator<TrafficVideoPlayBean> reduceStream = beanStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficVideoPlayBean>forBoundedOutOfOrderness(Duration.ofSeconds(5L)).withTimestampAssigner(new SerializableTimestampAssigner<TrafficVideoPlayBean>() {
            @Override
            public long extractTimestamp(TrafficVideoPlayBean trafficVideoPlayBean, long l) {
                return trafficVideoPlayBean.getTs();
            }
        })).keyBy(new KeySelector<TrafficVideoPlayBean, String>() {
            @Override
            public String getKey(TrafficVideoPlayBean trafficVideoPlayBean) throws Exception {
                return trafficVideoPlayBean.getMid();
            }
        }).window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                .reduce(new ReduceFunction<TrafficVideoPlayBean>() {
                    @Override
                    public TrafficVideoPlayBean reduce(TrafficVideoPlayBean v1, TrafficVideoPlayBean v2) throws Exception {
                        v1.setVideoplayedcount(v1.getVideoplayedcount() + v2.getVideoplayedcount());
                        v1.setPersonwatchedcount(v1.getPersonwatchedcount() + v2.getPersonwatchedcount());
                        v1.setPlayedtimesum(v1.getPlayedtimesum() + v2.getPlayedtimesum());
                        return v1;
                    }
                }, new WindowFunction<TrafficVideoPlayBean, TrafficVideoPlayBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow timeWindow, Iterable<TrafficVideoPlayBean> iterable, Collector<TrafficVideoPlayBean> collector) throws Exception {
                        TrafficVideoPlayBean next = iterable.iterator().next();
                        next.setStt(DateFormatUtil.toYmdHms(timeWindow.getStart()));
                        next.setEdt(DateFormatUtil.toYmdHms(timeWindow.getEnd()));
                        next.setTs(System.currentTimeMillis());
                        collector.collect(next);
                    }
                });
        reduceStream.print("reduce>>>>>");

        //TODO 关联维度章节名称
        SingleOutputStreamOperator<TrafficVideoPlayBean> resultStream = reduceStream.map(new RichMapFunction<TrafficVideoPlayBean, TrafficVideoPlayBean>() {

            DruidDataSource dataSource = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                dataSource = DruidPhoenixDSUtil.getDataSource();
            }

            @Override
            public TrafficVideoPlayBean map(TrafficVideoPlayBean trafficVideoPlayBean) throws Exception {
                // select * from t where id = 'v.id'
                // 关联DIM_CHAPTER_INFO商品表
                String videoId = trafficVideoPlayBean.getVideoId();
                JSONObject dimChapterInfo = DimUtil.getDimInfo(dataSource.getConnection(), "DIM_CHAPTER_INFO", new Tuple2<>("VIDEO_ID", videoId));
                if (dimChapterInfo != null) {
                    trafficVideoPlayBean.setChapterId((dimChapterInfo.getString("id")));
                    trafficVideoPlayBean.setChapterName(dimChapterInfo.getString("chapterName"));
                }
                return trafficVideoPlayBean;
            }
        });

        resultStream.print("result>>>>>");
        resultStream.addSink(ClickHouseUtil.getClickHouseSink("insert into dws_traffic_video_play_window values(?,?,?,?,?,?,?,?)"));
        //TODO 执行任务
        env.execute(groupId);
    }
}
